#include <opencv2/opencv.hpp>
#include <kinect.h>
using namespace std;
using namespace cv;
void mfilter(Mat& input,int lag,int th) {
	int rows = input.rows, cols = input.cols;
	int squ = (lag * 2 + 1)	* (lag * 2 + 1);
	Mat copy, result;
	input.copyTo(copy);
	input.copyTo(result);
	if (rows == 0 || cols == 0)
		return;
//#pragma omp parallel for
	for (int i = lag; i < rows - lag; i++) {
		for (int j = lag; j < cols - lag; j++) {
			int mean = 0, sum = 0, cur = copy.at<UINT16>(i, j), nz = 0;
			for (int p = -lag; p < lag + 1; p++) {
				for (int q = -lag; q < lag + 1; q++) {
					sum += copy.at<UINT16>(i + p, j + q);
					if (copy.at<UINT16>(i + p, j + q) != 0)
						nz++;
				}
			}
			if (nz > 0) {
				mean = sum / squ;
				if (abs(cur - mean) >mean*th/1000) {
					input.at<UINT16>(i, j) = 0;
				}
				else
				{
					input.at<UINT16>(i, j) = cur;
				}
			}
		}
	}
	//result.convertTo(result, CV_16UC1, 16);
	//imshow("img", input);
};
void maincv() {
	Mat img,imgt;
	namedWindow("img");
	int x=0, y=0,lag=0,th=0;
	createTrackbar("x", "img", &x, 512, NULL);
	createTrackbar("y", "img", &y, 424, NULL);
	createTrackbar("size", "img", &lag, 7, NULL);
	createTrackbar("th", "img", &th, 2000, NULL);
	img = imread("0.png",-1);
	//imshow("img", img);
	while (waitKey(1000)) {
		img.copyTo(imgt);
		auto time = clock();
		int i = 0;
		//while (i++ < 1000) {
		mfilter(imgt, lag,th);
		//}
		cout << clock() - time << endl;
		//line(imgt,Point(x,0),Point(x,424),65535,1);
		//line(imgt, Point(0, y), Point(512, y), 65535, 1);
		//cout << img.at<UINT16>(y,x)<<endl;
		imgt.convertTo(imgt, CV_16UC1, 16);
		imshow("1", imgt);
	};
}